const MD5Utils = require('MD5.js');
var barcode = require('barcode.js');
var qrcode = require('qrcode.js');

//这个是通过，app_id和private_secrect得到的，这两个值不变，app_token就不会变
//const app_token = '44d8f578f77c7efad164c237eb05cd492e227a017523b65b8392e7ddc6d1a0b0ab4443bf8fab900540afad3276823471';
//const security_code = 'Ct021WjY';

function formatNumber(n) {
  const num = n.toString();
  return num[1] ? num : `0${num}`;
}

function formatTime(date, type) {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  let time = '';
  switch (type) {
    case 1:
      time = `${[year, month, day].map(formatNumber).join('.')}`;
      break;
    case 2:
      time = `${[year, month, day].map(formatNumber).join('.')} ${[hour, minute].map(formatNumber).join(':')}`;
      break;
    default:
      time = `${[year, month, day].map(formatNumber).join('.')} ${[hour, minute, second].map(formatNumber).join(':')}`;
  }
  return time;
}


///// luyou add
Date.prototype.Format = function (fmt) { 
  var o = {
    "M+": this.getMonth() + 1, //月份 
    "d+": this.getDate(), //日 
    "h+": this.getHours(), //小时 
    "m+": this.getMinutes(), //分 
    "s+": this.getSeconds(), //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds() //毫秒 
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}


//获得版本数字
function getVersionNum(version){
  return version.replace(/\./g, "").replace("V", "").replace("v", "");
}


/* function getSign(req_data) {
  req_data.app_token = app_token;
  var newkey = Object.keys(req_data).sort();
  var sign = "";

  for (var i = 0; i < newkey.length; i++) {//遍历newObj数组
    if (i != newkey.length - 1) {
      sign += newkey[i];
      sign += "=";
      sign += req_data[newkey[i]];
      sign += "&";
    } else {
      sign += newkey[i];
      sign += "=";
      sign += req_data[newkey[i]];
    }
   
  }
  sign += security_code;
  return MD5Utils.hexMD5(sign);
} */




/**
function getSignWithnotSecutiryCode(req_data) {
  req_data.app_token = app_token;
  var newkey = Object.keys(req_data).sort();
  var sign = "";

  for (var i = 0; i < newkey.length; i++) {//遍历newObj数组
    if (i != newkey.length - 1) {
      sign += newkey[i];
      sign += "=";
      sign += req_data[newkey[i]];
      sign += "&";
    } else {
      sign += newkey[i];
      sign += "=";
      sign += req_data[newkey[i]];
    }

  }
  //sign += security_code;

  return MD5Utils.hexMD5(sign);
}
 */

//根据当前经纬计算距离
function getDistance(lat1, lng1, lat2, lng2) {
  lat1 = lat1 || 0;
  lng1 = lng1 || 0;
  lat2 = lat2 || 0;
  lng2 = lng2 || 0;

  var rad1 = lat1 * Math.PI / 180.0;
  var rad2 = lat2 * Math.PI / 180.0;
  var a = rad1 - rad2;
  var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;

  var r = 6378137;
  return r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))
}

//把doc_url得图片地址整合到list中
function mergePic(doc_url,list) {
  var doc_url_key = Object.keys(doc_url)
  for (var i = 0; i < list.length; i++) {
    var item_goods_pic_info_str = JSON.parse(list[i].item_goods_pic_info)[0].path_id;
    for(var e = 0;e<doc_url_key.length;e++){
      if (item_goods_pic_info_str === doc_url_key[e]){
        //涉及https访问证书问题     .replace("https", "http")
        list[i].item_goods_pic_info = doc_url[doc_url_key[e]].replace("https", "http")
      }
    }    
  }
  console.log("list-------------" + list)
  return list
}

//把doc_url得图片地址整合到list中   --商品详情页
function mergePicMsg(doc_url, list) {
  var doc_url_key = Object.keys(doc_url)
  var list_pic_info = JSON.parse(list[0].pic_info)[0].path_id;
  for (var i = 0; i < doc_url_key.length; i++) {
    if (list_pic_info === doc_url_key[i]) {
        list[0].pic_info = doc_url[doc_url_key[i]].replace("https", "http")
        //计算返款金额，保留两位小数（避免0.0098888情况） 映射到参数ts_price上
        var returnMomeny = (list[0].market_price - list[0].discount_price).toFixed(2);
        list[0].ts_price = returnMomeny;
        break
    }
  }
  console.log("list-------------" + list)
  return list
}


function convert_length(length) {
  return Math.round(wx.getSystemInfoSync().windowWidth * length / 750);
}

function showBrcode(id, code, width, height) {
  barcode.code128(wx.createCanvasContext(id), code, convert_length(width), convert_length(height))
}

function showQrcode(id, code, width, height) {
  qrcode.api.draw(code, {
    ctx: wx.createCanvasContext(id),
    width: convert_length(width),
    height: convert_length(height)
  })
}
//luyou end 


//导出接口--必须要写 
module.exports = {
  formatNumber,
  formatTime,
  //getSign,
  //getSignWithnotSecutiryCode,
  getVersionNum,
  getDistance,
  mergePic,
  showBrcode,
  showQrcode,
  mergePicMsg,
};
